package org.ricks.virtual;

import org.ricks.ioc.utils.Logger;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class PlayerManager {
    private static final Map<String, Player> allPlayers = new ConcurrentHashMap<>();
    private static volatile boolean isShuttingDown = false;

    static {
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            isShuttingDown = true;
            List<Player> players = new ArrayList<>(allPlayers.values());
            for (Player player : players) {
                try {
                    player.close();
                } catch (Exception e) {
                    Logger.error("Failed to close player during shutdown: " + player.id, e);
                }
            }
        }));
    }

    public static void registerPlayer(Player player) {
        if (isShuttingDown) {
            throw new IllegalStateException("System is shutting down, cannot register new players");
        }
        allPlayers.put(player.id, player);
    }

    public static void unregisterPlayer(Player player) {
        System.err.println("正在解绑 playerId:" + player.id + " , player:" + player);
        allPlayers.remove(player.id);
    }

    public static Player getPlayer(String id) {
        return allPlayers.get(id);
    }

    public static List<Player> getAllPlayers() {
        return new ArrayList<>(allPlayers.values());
    }

    // 健康检查方法
    public static Map<String, Boolean> getHealthStatus() {
        Map<String, Boolean> status = new ConcurrentHashMap<>();
        allPlayers.forEach((id, player) -> status.put(id, player.isHealthy()));
        return status;
    }

    // 监控统计
    public static void logStatistics() {
        allPlayers.forEach((id, player) -> {
            Logger.info("Player " + id +
                    " stats: processed=" + player.getProcessedTasks() +
                    ", rejected=" + player.getRejectedTasks() +
                    ", pending=" + player.getPendingTasks() +
                    ", avgTime=" + player.getAverageProcessingTimeMs() + "ms" +
                    ", slowTasks=" + player.getSlowTaskCount() +
                    ", criticalSlow=" + player.getCriticalSlowTaskCount());
        });
    }
}
